//
//  UIImage+Compress.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/30.
//

import UIKit

extension UIImage {
    static func compressImage(_ image: UIImage, maxSizeKB: Int) -> Data? {
        var compression: CGFloat = 1.0
        let maxFileSize = maxSizeKB * 1024 // 转换为字节
        var imageData: Data?
        
        // 逐步降低质量，直到满足大小要求
        while compression > 0 {
            imageData = image.jpegData(compressionQuality: compression)
            if let data = imageData, data.count <= maxFileSize {
                return data
            }
            compression -= 0.1 // 每次降低 10% 质量
        }
        
        return imageData // 如果仍然太大，返回最低质量的数据
    }
}

